package com.health.viewscontrols;

import com.health.BuildConfig;
import com.health.R;
import com.health.tools.DESUtil;
import com.health.tools.GlobalConts;
import com.health.tools.ResultTextDialog;
import com.health.tools.SPUtil;
import com.health.viewscontrols.settings.MainActivity_Menu_Settings_JTYS;
import com.health.webservices.ZCMWebService;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 注册界面
 */

public class RegisterActivity extends NovaActivity implements OnClickListener {

	private final static String ADDSTR = "1Y";

	protected static final String TAG = "RegisterActivity";
	private TextView tv_version;
	private EditText ed_xlh;// 序列号
	private EditText ed_zcm;// 注册码
	private Button btn_zc;// 注册
	private Button btn_sy;// 试用
	private Button btn_hqzcm;// 获取注册码
	private ImageView iv_setting;// 设置
	private ResultTextDialog resultDialog;
	private int sumSize;
	private int successCount;
	private ProgressDialog mProgressDialog;
	// 获得SharedPreferences.Editor对象
	TextView zhuce_tishi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		// 隐藏标题栏
		setContentView(R.layout.register_ac);

		findViews();
		setListeners();
		setDatas();
	}

	@Override
	public void findViews() {
		tv_version = (TextView) findViewById(R.id.tv_version);
		String versionName = GlobalConts.getVerName(RegisterActivity.this);
		if (!TextUtils.isEmpty(versionName)) {
			tv_version.setText("V  "+ BuildConfig.VERSION_NAME);
		} else {
			tv_version.setText("");
		}
		zhuce_tishi=findViewById(R.id.zhuce_tishi);

		ed_xlh = (EditText) findViewById(R.id.ed_xlh);
		ed_zcm = (EditText) findViewById(R.id.ed_zcm);
		btn_zc = (Button) findViewById(R.id.btn_zc);
		btn_sy = (Button) findViewById(R.id.btn_sy);
//		btn_sy.setVisibility(View.GONE);
		if (resultDialog == null) {
			resultDialog = new ResultTextDialog(RegisterActivity.this);
		}
		btn_hqzcm = (Button) findViewById(R.id.btn_hqzcm);
		iv_setting = (ImageView) findViewById(R.id.iv_setting);
	}

	@Override
	public void setListeners() {
		btn_hqzcm.setOnClickListener((android.view.View.OnClickListener) this);
		btn_zc.setOnClickListener((android.view.View.OnClickListener) this);
		btn_sy.setOnClickListener((android.view.View.OnClickListener) this);
		iv_setting.setOnClickListener((android.view.View.OnClickListener) this);
	}

	private void setDatas() {
		String str_imei = GlobalConts.generateIMEI(getApplicationContext());
//		String str_imei = "4A5F634346A82B95";
//		String str_imei = "E09A65D335573AB5";
		if (!TextUtils.isEmpty(str_imei)) {
			Log.w("m_szUniqueID444", str_imei);
			// str_imei = "adb";
			ed_xlh.setText(str_imei);
			saveImeiData(str_imei);
			NovaApplication.setImei(str_imei);
		} else {
			showTextDialog("未获取到序列号，请连接WiFi后重试");
		}
	}

	private void saveImeiData(String str_imei) {
		SPUtil.setRegisterImei(RegisterActivity.this, str_imei);
	}

	private void getIMEIData() {
		// new Thread(runnable).start();// 线程启动
		if (!GlobalConts.isNetworkAvailable(RegisterActivity.this)) {
			showTextDialog("请先检查网络");
			return;
		}
		initProgressDialog();
		showProgressDialog("正在获取数据...");
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				// System.out.println("webservice");
				try {
					new ZCMWebService(mContext) {

						@Override
						public void start(String message) {
							super.start(message);
							System.out.println("test111" + message);
						}

						@Override
						public void onSynchronize(String message, int syncCount, int dataSize) {
							super.onSynchronize(message, syncCount, dataSize);
						}

						@Override
						public void complete(final String message) {
							super.complete(message);
							cancelProgressDialog();
							if (mProgressDialog != null) {
								mProgressDialog.dismiss();
								mProgressDialog.cancel();
							}
							runOnUiThread(new Runnable() {

								@Override
								public void run() {

									// String str_zcm =
									// MyPreferences.getString("registerZCMAll",
									// "");
									String str_zcm = SPUtil.getRegisterZCMAll(mContext);
									Log.e(TAG, str_zcm);

									if (TextUtils.isEmpty(str_zcm) || str_zcm.length() < 6) {
										resultDialog.setText("获取注册码失败");
										resultDialog.showCancleLong();
									} else {
										// saveZCMData(str_zcm);
										String content = NovaApplication.getImei() + str_zcm.substring(0, 6) + ADDSTR;
										// 加密数据
										ed_zcm.setText(getJMData(content));
										// String decryptData =
										// decrypt(encryptData, key);
									}

								}
							});
						}

						public void onError(String message) {
							cancelProgressDialog();
							if (mProgressDialog != null) {
								mProgressDialog.dismiss();
								mProgressDialog.cancel();
							}
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									resultDialog.setText("获取验证码失败,请检查上传地址是否有误！");
									resultDialog.showCancleLong();

								}
							});
						};
					}.synchrodata(NovaApplication.getImei());
				} catch (Exception e) {
					e.printStackTrace();
					if (mProgressDialog != null) {
						mProgressDialog.dismiss();
						mProgressDialog.cancel();
					}
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							resultDialog.setText("数据同步失败");
							resultDialog.showCancleLong();
						}
					});
				}
			}
		};
		handler.sendMessage(new Message());

	}

	private void initProgressDialog() {
		mProgressDialog = new ProgressDialog(RegisterActivity.this);
		// progressDialog.setIcon(R.drawable.ic_launcher);
		mProgressDialog.setTitle("正在同步数据");
		mProgressDialog.setMessage("请稍候...");
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	}

	private void jumpNextActivity() {
		startActivity(new Intent(getApplication(), HomeDataDownloadActivity.class));
		RegisterActivity.this.finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_hqzcm:
			// 注册
			getIMEIData();
			break;
		case R.id.btn_zc:
			// 注册
			yzZCM();
			break;
		case R.id.btn_sy:
			// 试用
			// editor.putBoolean("isShiYong", true);
			// editor.putString("registerXZQ", "370188");
			// editor.commit();
			SPUtil.setIsShiYong(RegisterActivity.this, true);
			SPUtil.setRegisterXZQ(RegisterActivity.this, "370188");
			jumpNextActivity();
			break;

		case R.id.iv_setting:
			Intent intent = new Intent(RegisterActivity.this, MainActivity_Menu_Settings_JTYS.class);
			startActivity(intent);
		default:
			break;
		}
	}

	/**
	 * 获取加密数据
	 * 
	 * @return
	 * @author 王婷婷
	 * @date 2017年9月7日 下午5:33:54
	 */
	private String getJMData(String str_content) {
		String str_jmContent = "";
		if (TextUtils.isEmpty(str_content)) {
			return str_jmContent;
		}
		System.out.println("原文1: " + str_content);
		if (str_content.length() != 24) {
			return str_jmContent;
		}

		System.out.println("原文: " + str_content);
		String key = "A1B2C3D4E5F60708";
		String encryptData;
		try {
			encryptData = DESUtil.encrypt(str_content, key);
			encryptData.replace("=", "");
			StringBuffer s1 = new StringBuffer(encryptData);

			int index = 0;

			for (index = 5; index < s1.length(); index += 6) {
				s1.insert(index, '-');
			}

			str_jmContent = s1.toString();
			System.out.println(s1);
			System.out.println("加密后: " + encryptData);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return str_jmContent;
	}

	/**
	 * 验证注册码
	 * 
	 * @author 王婷婷
	 * @date 2017年9月8日 上午10:41:09
	 */
	private void yzZCM() {
		if (TextUtils.isEmpty(NovaApplication.getImei())) {
			showTextDialog("未获取到序列号");
			return;
		}
		if (TextUtils.isEmpty(NovaApplication.getXzqhNo())) {
			showTextDialog("未获取到注册码");
			return;
		}
		String text_jm = ed_zcm.getText().toString();
		// String content = NovaApplication.getImei() +
		// MyPreferences.getString("registerZCMAll", "").substring(0, 6)
		// + "1Y";
		String content = null;
		if (!TextUtils.isEmpty(SPUtil.getRegisterZCMAll(RegisterActivity.this))) {

			content = NovaApplication.getImei() + SPUtil.getRegisterZCMAll(RegisterActivity.this).substring(0, 6)
					+ "1Y";
		}

		if (TextUtils.isEmpty(text_jm)) {
			showTextDialog("请先获取注册码");
			return;
		}
		if (!getJMData(content).equals(text_jm)) {
			showTextDialog("注册码不正确");
			return;
		}
		// editor.putBoolean("isShiYong", false);
		// editor.commit();
		SPUtil.setIsShiYong(RegisterActivity.this, false);
		jumpNextActivity();
	}
}
